use clap::Parser;
use cocoon_tmxconvert::tmx_loader::load_tmx;
use serde_json;
use std::fs;
use std::path::PathBuf;

#[derive(clap::Parser)]
#[clap(author, version, about, long_about = None)]
struct Cli {
    #[clap(help = "TMX文件路径")]
    path: PathBuf,

    #[clap(help = "输出文件路径")]
    output: PathBuf,

    #[clap(action = clap::ArgAction::SetTrue, help = "是否格式化输出", short, long)]
    pretty: bool,// 是否格式化输出

    #[clap(default_value = "json", help = "输出文件格式", short, long, value_parser = ["json", "bin"])]
    format: String,

    #[clap(short, long, help = "工作目录")]
    work_dir: PathBuf,
}

fn main() {
    let args = Cli::parse();
    
    match load_tmx(&args.path, &args.work_dir) {
        Ok(tmx_data) => {
            match args.format.as_str() {
                "json" => {
                    match if args.pretty {
                        serde_json::to_string_pretty(&tmx_data)
                    } else {
                        serde_json::to_string(&tmx_data)
                    } {
                        Ok(json) => {
                            if let Err(e) = fs::write(&args.output, json) {
                                eprintln!("Failed to write JSON to output file: {}", e);
                            }
                        }
                        Err(e) => {
                            eprintln!("Failed to serialize TMX data to JSON: {}", e);
                        }
                    }
                }
                "bin" => {
                    match xrserializer::Serializer::serialize(&tmx_data) {
                        Ok(bin) => {
                            if let Err(e) = fs::write(&args.output, bin) {
                                eprintln!("Failed to write binary to output file: {}", e);
                            }
                        }
                        Err(e) => {
                            eprintln!("Failed to serialize TMX data to binary: {}", e);
                        }
                    }
                }
                _ => {
                    eprintln!("Unsupported output format: {}", args.format);
                }
            }
        }
        Err(e) => {
            eprintln!("Failed to load TMX file: {}", e);
        }
    }
}
